<?php
/**
 *
 * @package default
 * @author QuangNghia
 */
class NFile
{
	/**
	 * This function create:
	 * 1. upload folder in baseUrl path.
	 * 2. {model_class_name}_model folder inside [1]
	 * 
	 * @param string $model 
	 * @param string $path
	 * @return string
	 * @author Nguyen Quang Nghia
	 */
	public static function uploadFolder($model, $path = 'upload/') 
	{
		$path = $path . get_class($model) . '_model'; 
		return self::createPath($path, true);
	}
	
	/**
	* Create nested folder for in the path if not exist 
	* and return the original path in lowercase
	* the path MUST NOT end with slash
	*/
	public static function createPath($path, $add_date_sub_folder=false)
	{
		$path_to_go = '';
		if($add_date_sub_folder) $path .= '/' . date('Y_M');
		$path = strtolower($path);

		// if this path has not been created yet
		if(! is_dir($path)) {
			$folders = explode('/',$path);
			foreach ($folders as $folder) {
				$path_to_go .= $folder . DIRECTORY_SEPARATOR;
				// create folder only if it's not existed
				if(!is_dir($path_to_go)) @mkdir($path_to_go, 0777, true);
			}
		}
		return strtolower($path);
	}

	public static function copy_dir($source, $destination) 
	{
		if ( is_dir( $source ) ) {
			@mkdir( $destination, 0777, true );
			$directory = dir( $source );
			while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
				if ( $readdirectory == '.' || $readdirectory == '..' ) {
					continue;
				}
				$PathDir = $source . '/' . $readdirectory; 
				if ( is_dir( $PathDir ) ) {
					copy_dir( $PathDir, $destination . '/' . $readdirectory );
					continue;
				}
				copy( $PathDir, $destination . '/' . $readdirectory );
			}
	 
			$directory->close();
		}else {
			copy( $source, $destination );
		}
	}
}
?>